﻿using Application.Commons.Data;
using Domain.Entities.Customers;
using FrameworkCore.Attributes;
using FrameworkCore.Helpers;
using FrameworkCore.Models;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;

namespace NM.Module.Cust.API.Commands.Delete;

#nullable disable

/// <summary>
/// 删除用户
/// </summary>
[Map(typeof(Customer))]
public class DeleteCustomerCommand : IRequest<Result<bool>>
{
    /// <summary>
    /// 用户主键
    /// </summary>
    [Required(ErrorMessage = "用户主键必传")]
    public List<long> CustomerIds { get; set; }
}

public class DeleteCustomerCommandHandler : IRequestHandler<DeleteCustomerCommand, Result<bool>>
{
    private readonly ApplicationDbContext _context;

    public DeleteCustomerCommandHandler(ApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<Result<bool>> Handle(DeleteCustomerCommand request, CancellationToken cancellationToken)
    {
        var items = await _context.Customers.Where(x => request.CustomerIds.Contains(x.Id)).ToListAsync(cancellationToken);
        ExceptionHelper.ThrowIfNull(items, "用户不存在");

        _context.Customers.RemoveRange(items);
        var result = await _context.SaveChangesAsync(cancellationToken) > 0;

        return await Result<bool>.SucceedAsync(result, result, ["删除失败"]);
    }
}